package interview;

public class lc142_circle {
    static class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
    }
    public static void main(String[] args) {

    }
    public static ListNode detectCycle(ListNode head) {
        //环形链表一般是双指针判断是否有环
        if(head == null)
            return null;
        int flag = 0;
        //首先判断是否有环
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast) {
                flag = 1;
                break;
            }
        }
        if(flag == 0)
            return null;
        //有环,利用数学推导得到，从头开始，和从相遇点开始到入环节点的距离相等
        ListNode node = head;
        while (node != slow){
            node = node.next;
            slow = slow.next;
        }
        return slow;
    }
}
